import React, { useRef, useState, useEffect } from 'react';
import { Modal, Button, Slider, Typography, Space, Progress, Tag } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined, SoundOutlined, DownloadOutlined } from '@ant-design/icons';

const { Text, Title } = Typography;

interface AudioPlayerProps {
  visible: boolean;
  text?: LEARNING.DetectionTextModel;
  onCancel: () => void;
}

const AudioPlayer: React.FC<AudioPlayerProps> = ({ visible, text, onCancel }) => {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [volume, setVolume] = useState(1);
  const [playbackRate, setPlaybackRate] = useState(1);

  useEffect(() => {
    if (visible && audioRef.current) {
      const audio = audioRef.current;
      
      const updateTime = () => setCurrentTime(audio.currentTime);
      const updateDuration = () => setDuration(audio.duration);
      const handleEnded = () => setIsPlaying(false);
      
      audio.addEventListener('timeupdate', updateTime);
      audio.addEventListener('loadedmetadata', updateDuration);
      audio.addEventListener('ended', handleEnded);
      
      return () => {
        audio.removeEventListener('timeupdate', updateTime);
        audio.removeEventListener('loadedmetadata', updateDuration);
        audio.removeEventListener('ended', handleEnded);
      };
    }
  }, [visible]);

  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.volume = volume;
      audioRef.current.playbackRate = playbackRate;
    }
  }, [volume, playbackRate]);

  const togglePlay = () => {
    if (audioRef.current) {
      if (isPlaying) {
        audioRef.current.pause();
      } else {
        audioRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };

  const handleSeek = (value: number) => {
    if (audioRef.current) {
      audioRef.current.currentTime = value;
      setCurrentTime(value);
    }
  };

  const formatTime = (time: number) => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  };

  const handleDownload = () => {
    if (text?.audio_url) {
      const link = document.createElement('a');
      link.href = text.audio_url;
      link.download = `${text.content.substring(0, 20)}.mp3`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  if (!text) return null;

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <SoundOutlined style={{ fontSize: 20 }} />
          <div>
            <div>音频播放器</div>
            <div style={{ fontSize: '12px', color: '#666' }}>检测文本音频</div>
          </div>
        </div>
      }
      open={visible}
      onCancel={onCancel}
      footer={[
        <Button key="download" icon={<DownloadOutlined />} onClick={handleDownload}>
          下载音频
        </Button>,
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
      ]}
      width={600}
      destroyOnClose
    >
      <div style={{ padding: '20px 0' }}>
        {/* 文本信息 */}
        <div style={{ marginBottom: 24, textAlign: 'center' }}>
          <Title level={4} style={{ margin: '0 0 8px 0' }}>
            {text.content}
          </Title>
          {text.pinyin && (
            <Text type="secondary" style={{ fontSize: '14px' }}>
              {text.pinyin}
            </Text>
          )}
          <div style={{ marginTop: 12 }}>
            <Space>
              <Tag color="blue">{text.category}</Tag>
              <Tag color={text.difficulty === 'easy' ? 'green' : text.difficulty === 'medium' ? 'orange' : 'red'}>
                {text.difficulty === 'easy' ? '简单' : text.difficulty === 'medium' ? '中等' : '困难'}
              </Tag>
            </Space>
          </div>
        </div>

        {/* 音频控件 */}
        {text.audio_url ? (
          <div>
            <audio ref={audioRef} src={text.audio_url} preload="metadata" />
            
            {/* 播放控制 */}
            <div style={{ textAlign: 'center', marginBottom: 20 }}>
              <Button
                type="primary"
                size="large"
                shape="circle"
                icon={isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                onClick={togglePlay}
                style={{ width: 60, height: 60, fontSize: 24 }}
              />
            </div>

            {/* 进度条 */}
            <div style={{ marginBottom: 20 }}>
              <Slider
                min={0}
                max={duration || 100}
                value={currentTime}
                onChange={handleSeek}
                tooltip={{ formatter: formatTime }}
              />
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
                <span>{formatTime(currentTime)}</span>
                <span>{formatTime(duration)}</span>
              </div>
            </div>

            {/* 音量控制 */}
            <div style={{ marginBottom: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <SoundOutlined />
                <span style={{ fontSize: '12px', width: 40 }}>音量</span>
                <Slider
                  style={{ flex: 1 }}
                  min={0}
                  max={1}
                  step={0.1}
                  value={volume}
                  onChange={setVolume}
                  tooltip={{ formatter: (value) => `${Math.round((value || 0) * 100)}%` }}
                />
                <span style={{ fontSize: '12px', width: 40 }}>{Math.round(volume * 100)}%</span>
              </div>
            </div>

            {/* 播放速度控制 */}
            <div style={{ marginBottom: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <span style={{ fontSize: '12px', width: 40 }}>速度</span>
                <Space>
                  {[0.5, 0.75, 1, 1.25, 1.5, 2].map(rate => (
                    <Button
                      key={rate}
                      size="small"
                      type={playbackRate === rate ? 'primary' : 'default'}
                      onClick={() => setPlaybackRate(rate)}
                    >
                      {rate}x
                    </Button>
                  ))}
                </Space>
              </div>
            </div>

            {/* 播放进度 */}
            <div style={{ background: '#f5f5f5', padding: 16, borderRadius: 8 }}>
              <div style={{ marginBottom: 8, fontSize: '14px', fontWeight: 500 }}>播放进度</div>
              <Progress
                percent={duration ? Math.round((currentTime / duration) * 100) : 0}
                size="small"
                status={isPlaying ? 'active' : 'normal'}
              />
            </div>
          </div>
        ) : (
          <div style={{ textAlign: 'center', padding: 40, color: '#999' }}>
            <SoundOutlined style={{ fontSize: 48, marginBottom: 16 }} />
            <div>该文本暂无音频文件</div>
          </div>
        )}

        {/* 文本详情 */}
        {text.description && (
          <div style={{ marginTop: 24, padding: 16, background: '#f9f9f9', borderRadius: 8 }}>
            <div style={{ marginBottom: 8, fontSize: '14px', fontWeight: 500 }}>文本说明</div>
            <Text type="secondary">{text.description}</Text>
          </div>
        )}

        {/* 使用统计 */}
        <div style={{ marginTop: 16, display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
          <span>使用次数: {text.usage_count || 0}</span>
          <span>正确率: {text.accuracy_rate ? `${(text.accuracy_rate * 100).toFixed(1)}%` : '-'}</span>
        </div>
      </div>
    </Modal>
  );
};

export default AudioPlayer;
